package com.example.demo.controller.wx;

import com.example.demo.util.FileUtil;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.bind.annotation.RestController;
import org.springframework.web.multipart.MultipartFile;

import javax.servlet.ServletOutputStream;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.*;

/**
 * <h3>reqister</h3>
 * <p>微信 Controller</p>
 *
 * @author : chenjunjie
 * @date : 2021-06-21 16:42
 **/
@RestController
@RequestMapping("/wx")
public class WxContrller {

    private final String ROOTPATH="src/main/resources/static/imgs/";

    @RequestMapping("/clocking")
    public void register(@RequestParam("file") MultipartFile[] files, HttpServletRequest request){
        System.out.println(files.length);
        String path = FileUtil.uploadToTempFolder(files[0]);
        System.out.println(path);
    }

    @RequestMapping("/downLoadImg")
    public void downLoadImg(String imgName, HttpServletResponse response){

        System.out.println(ROOTPATH+imgName);
        File file=new File(ROOTPATH+imgName);

        if(file.exists()) {
            try (BufferedInputStream bis = new BufferedInputStream(new FileInputStream(file));
                 ServletOutputStream os = response.getOutputStream()) {
                response.setContentType("application/x-download;charset=UTF-8");
                response.setCharacterEncoding("UTF-8");
                response.setHeader("Content-Disposition", "attachment;fileName="
                        + java.net.URLEncoder.encode(imgName, "UTF-8"));

                byte[] buffer = new byte[1024];
                int count;
                while ((count = bis.read(buffer)) != -1) {
                    os.write(buffer, 0, count);
                }
            } catch (FileNotFoundException e) {
                e.printStackTrace();
            } catch (IOException e) {
                e.printStackTrace();
            }
        }
    }


}
